package com.ist412.pocke;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ist412.pocke.DTO.ProfileDTO;
import com.ist412.pocke.SQL.Profile;

/**
 * This activity allows the user to edit the currently active Profile within the application.
 * If a profile exists, the fields are filled with information from the current ProfileDTO.
 * Otherwise, the fields are filled with information from a default ProfileDTO.
 * 
 * @author Rob
 * @version 1.1
 */
public class ProfileEditActivity extends Activity implements OnClickListener {
	 
	private boolean 		_profileExists;
	private ProfileDTO 		_profile;
	private final String[] 	_genders = {"Male", "Female", "Other"};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Remove title & Make fullscreen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
	    setContentView(R.layout.profile_edit);
	    
	    // Check if profile exists
	    _profileExists			= false;
	    
	    ArrayList<ProfileDTO> profiles = Profile.getProfile(this);
		
	    if (profiles.size() > 0) {
	    	_profileExists = true;
	    	// TODO Get profile by id
	    	// Assume last Profile is the one needed
	    	_profile = profiles.get(profiles.size() - 1);
	    } else {
	    	_profile = new ProfileDTO();
	    }
	    
	    //Log.e("Profiles","Profiles size: " + profiles.size());
	    
	    // Grab widgets
        Spinner spnGender		= (Spinner) findViewById(R.id.profileedit_spnGender);
        Button btnSave			= (Button) findViewById(R.id.profileedit_btnSave);
        Button btnCancel		= (Button) findViewById(R.id.profileedit_btnCancel);
        
        // Handle widgets
        btnSave.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        
        // Fill Gender spinner
        List<String> spinnerGenderValues = new ArrayList<String>();
        
        for (int i = 0; i < _genders.length; i++) {
        	spinnerGenderValues.add(_genders[i]);
        }
        
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, spinnerGenderValues);
        //spinnerArrayAdapter.setDropDownViewResource(R.layout.profile_edit);
        spnGender.setAdapter(spinnerArrayAdapter);
        
        // Fill fields with _profile information
        fillFields();
        
	} // end onCreate()
	
	@Override
	public void onResume() {
		super.onResume();
		
		fillFields();
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
			case R.id.profileedit_btnSave:
				if (saveProfile()) {
					finish();
				}
				break;
			case R.id.profileedit_btnCancel:
				finish();
				break;
		} // end switch(view v)
		
	} // end onClick()
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Fills fields in the Activity with informaiton from _profile. If _profileExists is true,
	 * then the fields are filled with information from _profile. Otherwise the information
	 * defaults to basic strings {"First", "Last"} and 0 for numeric values.
	 * 
	 * @return	boolean whether or not the operation is successful
	 * 
	 * TODO Handle return to determin success in filling field from ProfileDTO
	 */
	public final boolean fillFields() {
		// Grab widgets
		EditText edtFName		= (EditText) findViewById(R.id.profileedit_edtFirstName);
		EditText edtLName 		= (EditText) findViewById(R.id.profileedit_edtLastName);
		EditText edtAge 		= (EditText) findViewById(R.id.profileedit_edtAge);
		Spinner  spnGender		= (Spinner)  findViewById(R.id.profileedit_spnGender);
		EditText edtWeight		= (EditText) findViewById(R.id.profileedit_edtWeight);
		EditText edtFeet 		= (EditText) findViewById(R.id.profileedit_edtFeet);
		EditText edtInch		= (EditText) findViewById(R.id.profileedit_edtInch);
		EditText edtArm			= (EditText) findViewById(R.id.profileedit_edtArm);
		EditText edtShoulder	= (EditText) findViewById(R.id.profileedit_edtShoulder);
		EditText edtChest		= (EditText) findViewById(R.id.profileedit_edtChest);
		EditText edtWaist		= (EditText) findViewById(R.id.profileedit_edtWaist);
		EditText edtThigh		= (EditText) findViewById(R.id.profileedit_edtThigh);
		EditText edtCalf		= (EditText) findViewById(R.id.profileedit_edtCalf);
		
		// Fill from information from _profile if possible, otherwise use default values
		if (_profileExists) {
			edtFName.setText(_profile.getFName());
			edtLName.setText(_profile.getLName());
			edtAge.setText(Integer.toString(_profile.getAge()));

			ArrayAdapter<String> adapter = (ArrayAdapter<String>) spnGender.getAdapter();
			int pos = adapter.getPosition(_profile.getGender());
			spnGender.setSelection(pos);
			
			edtWeight.setText(Integer.toString(_profile.getWeight()));
			edtFeet.setText(Integer.toString(_profile.getHFeet()));
			edtInch.setText(Integer.toString(_profile.getHInch()));
			// BMI is calculated
			edtArm.setText(Integer.toString(_profile.getBodyArm()));
			edtShoulder.setText(Integer.toString(_profile.getBodyShoulder()));
			edtChest.setText(Integer.toString(_profile.getBodyChest()));
			edtWaist.setText(Integer.toString(_profile.getBodyWaist()));
			edtThigh.setText(Integer.toString(_profile.getBodyThigh()));
			edtCalf.setText(Integer.toString(_profile.getBodyCalf()));
		} else {
			edtFName.setText("First");
			edtLName.setText("Last");
			edtAge.setText("0");
			edtWeight.setText("0");
			edtFeet.setText("0");
			edtInch.setText("0");
			edtArm.setText("0");
			edtShoulder.setText("0");
			edtChest.setText("0");
			edtWaist.setText("0");
			edtThigh.setText("0");
			edtCalf.setText("0");
		} // end if .. else (_profileExists)
		
		// Signal successful fill
		return true;
		
	} // end fillFields()
	
	/**
	 * Gathers all the information from the activity's form then calls the associated set
	 * methods within _profile. Depending on _profileExists, calls createProfile or
	 * updateProfile using _profile as the ProfileDTO.
	 * 
	 * @return	Boolean signaling success or failure in saving the ProfileDTO object
	 */
	public final boolean saveProfile() {
		// Grab widgets
		EditText edtFName		= (EditText) findViewById(R.id.profileedit_edtFirstName);
		EditText edtLName 		= (EditText) findViewById(R.id.profileedit_edtLastName);
		EditText edtAge 		= (EditText) findViewById(R.id.profileedit_edtAge);
		Spinner  spnGender		= (Spinner)  findViewById(R.id.profileedit_spnGender);
		EditText edtWeight		= (EditText) findViewById(R.id.profileedit_edtWeight);
		EditText edtFeet 		= (EditText) findViewById(R.id.profileedit_edtFeet);
		EditText edtInch		= (EditText) findViewById(R.id.profileedit_edtInch);
		EditText edtArm			= (EditText) findViewById(R.id.profileedit_edtArm);
		EditText edtShoulder	= (EditText) findViewById(R.id.profileedit_edtShoulder);
		EditText edtChest		= (EditText) findViewById(R.id.profileedit_edtChest);
		EditText edtWaist		= (EditText) findViewById(R.id.profileedit_edtWaist);
		EditText edtThigh		= (EditText) findViewById(R.id.profileedit_edtThigh);
		EditText edtCalf		= (EditText) findViewById(R.id.profileedit_edtCalf);
		
		// Variables to hold information
		String fname, lname, gender;
		int age, weight, feet, inch, arm, shoulder, chest, waist, thigh, calf;
		
		// Fill Variables
		fname 		= edtFName.getText().toString();
		lname		= edtLName.getText().toString();
		age			= getIntIfEntered(edtAge);
		gender 		= spnGender.getSelectedItem().toString();
		//Log.e("ProfileEdit","Gender from edtGender: " + gender);
		weight 		= getIntIfEntered(edtWeight);
		feet 		= getIntIfEntered(edtFeet);
		inch 		= getIntIfEntered(edtInch);
		
		if (inch > 12) {
			showToast("Invalid inches entered");
			edtInch.setText("");
			edtInch.requestFocus();
		}
		
		arm			= getIntIfEntered(edtArm);
		shoulder	= getIntIfEntered(edtShoulder);
		chest		= getIntIfEntered(edtChest);
		waist		= getIntIfEntered(edtWaist);
		thigh		= getIntIfEntered(edtThigh);
		calf		= getIntIfEntered(edtCalf);
		
		// Set new values to profile
		_profile.setFName(fname);
		_profile.setLName(lname);
		_profile.setAge(age);
		_profile.setGender(gender);
		_profile.setWeight(weight);
		_profile.setHFeet(feet);
		_profile.setHInch(inch);
		_profile.setBodyArm(arm);
		_profile.setBodyShoulder(shoulder);
		_profile.setBodyChest(chest);
		_profile.setBodyWaist(waist);
		_profile.setBodyThigh(thigh);
		_profile.setBodyCalf(calf);
		
		// Determine create or update actions
		if (_profileExists) {
			//Log.e("trace","\tUpdating");
			Profile.updateProfile(this, _profile);
		} else {
			//Log.e("trace","\tCreating");
			Profile.createProfile(this, _profile);
		}
		
		// Signal success in updating or creating the profile
		return true;
	} // end saveProfile()
	
	/**
	 * Attempts to convert entered String into an int
	 * @param edt	EditText widget to use
	 * @return	int conversion of string if successful, 0 otherwise
	 */
	private final int getIntIfEntered(EditText edt) {
		int ret = 0;
		
		if (edt.getText().toString().length() > 0) {
			try {
				ret = Integer.parseInt(edt.getText().toString());
			} catch (Exception e) { return 0; }
		} else {
			ret = 0;
		}
		
		return ret;
	}
	
	public void showToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	
} // end class ProfileActivity